package com.taru.houseapp.controller;

import com.taru.houseapp.commen.JsonResult;
import com.taru.houseapp.entity.User;
import com.taru.houseapp.service.IUserService;
import com.taru.houseapp.until.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    IUserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public JsonResult login(@RequestBody User user){
        JsonResult result=null;
        if(user.getUserName()==null|| user.getPassword()==null||user.getUserName().length()<=0||user.getPassword().length()<=0){
            result=new JsonResult(404,"参数错误");
            return result;
        }
        try{
            User user1=userService.queryUserByLogin(user);
            if(user1!=null){
                Map<String,Object> hashMap=new HashMap<>();
                String token= JwtUtil.createToken(user.getId());
                hashMap.put("tokenHead","Bearer");
                hashMap.put("tokenHeaderName","Authorization");
                hashMap.put("user",user1);
                hashMap.put("token",token);
                result=new JsonResult(200,"登录成功",hashMap);
            }else {
                result=new JsonResult(404,"用户名密码错误或token过期");
            }
        }catch (Exception e){
            e.printStackTrace();
            result=new JsonResult(500,"服务器内部错误",e.getMessage());
        }
        return result;
    }
}
